mui.init({
	beforeback: function() {
		//获得列表界面的webview  
		var list = plus.webview.getWebviewById('me.html');;
		//触发列表界面的自定义事件（refresh）,从而进行数据刷新  
		mui.fire(list, 'refresh');
		//返回true，继续页面关闭逻辑  
		return true;
	}
});
//mui("#user_id").html(localStorage.getItem('user_id'));
/*
var userinfo = localforage.getItem('userinfo', function(err, val){
	console.log(val.user_id);
});*/
var userinfo = app.getState();
console.log(JSON.stringify(userinfo));
var uid = userinfo.user_id;
document.getElementById('user_id').innerHTML = uid;
document.getElementById('phone').innerHTML = userinfo.phone;
//var userinfo = get_data('userinfo');
document.getElementById('username').value = userinfo.name || '';
// document.getElementById("head-img").src = app.avatar(uid, '../../static/images/1.png');

//var img1 = '../../static/images/1.png';
var img2 = userinfo.avatar;

document.getElementById("head-img").src = userinfo.avatar;

//document.querySelector('.head-img').setAttribute('onerror', "javascript:this.src='" + img1 + "'");
//console.log('1111');


mui.plusReady(function() {
	var getCodeBox = document.getElementById('getCode');
	getCodeBox.addEventListener('tap', function() {
		//localStorage.removeItem('_send_code');
		var c1 = 60,
			phone = userinfo.phone;
		//var phone = 13873150575;
		if(phone == '') {
			plus.nativeUI.toast("手机号码不能为空");
			return;
		}
		var btnArray = ['确定', '取消'];
		mui.confirm('我们将发送验证码短信到下面的号码：\n' + phone, '确认手机号码', btnArray, function(e) {
			if(e.index == 0) {
				mui.get(apiurl + 'index/sms', {
					'phone': userinfo.user_name
				}, function(res) {
					console.log(JSON.stringify(res));
					if(res.status == 1) {
						plus.nativeUI.toast('发送短信成功');
						//发送短信成功
						//localStorage.setItem('_send_code', res.ck_code);
					} else {
						plus.nativeUI.toast(res.msg);
						getCodeBox.innerHTML = '获取验证码';
						getCodeBox.removeAttribute('disabled');
						c1 = 60;
						return;
					}
					var code1 = setInterval(function() {
						getCodeBox.innerHTML = c1 + '秒后重新获取';
						c1 = c1 - 1;
						if(c1 >= 0) {
							getCodeBox.setAttribute("disabled", "disabled");
						} else {
							getCodeBox.innerHTML = '获取验证码';
							getCodeBox.removeAttribute('disabled');
							c1 = 60;
							clearInterval(code1);
						}
					}, 1000);
				});
			}

		})

	});
	document.getElementById('setbtn').addEventListener('tap', function(event) {
		var username = document.getElementById('username').value;
		var newtel = document.getElementById('newtel').value;
		var code = document.getElementById('code').value;
		if(newtel != '') {
			if(code == '') {
				mui.alert('更改手机号验证码不能为空');
				return;
			}
		}
		if(!username) {
			mui.alert('请输入昵称');
			return false;
		}
		setinfo = {
			user_id: uid,
			name: username,
			newtel : newtel,
			code : code
			//avatar : userinfo.avatar
		};
		//console.log(setinfo);
		//console.log(apiurl + 'user/setme');
		mui.post(apiurl + 'user/setme', setinfo, function(res) {
			console.log(res.msg);
			if(res.status > 0) {
				//userinfo.name = username;
				//localStorage.setItem('userinfo', userinfo);
				console.log(JSON.stringify(res));
				userinfo.name = username;
				if(newtel && code) {
					userinfo.phone = newtel;
				}
				app.setState(userinfo);
				app.setUsers(userinfo);
			}
			mui.toast(res.msg);
			var list = plus.webview.getWebviewById('me.html');;
			//触发列表界面的自定义事件（refresh）,从而进行数据刷新  
			mui.fire(list, 'refresh');
			plus.webview.currentWebview().close();
			//
		}, 'json');
	});
})

document.addEventListener('updateHeadImg', function(event) {
	var userinfo = app.getState();
	document.getElementById("head-img").src = userinfo.avatar;
});
//更换头像
mui(".mui-table-view-cell").on("tap", "#head", function(e) {
	if(mui.os.plus) {
		var a = [{
			title: "拍照"
		}, {
			title: "从手机相册选择"
		}];
		plus.nativeUI.actionSheet({
			title: "修改头像",
			cancel: "取消",
			buttons: a
		}, function(b) {
			switch(b.index) {
				case 0:
					break;
				case 1:
					getImage();
					break;
				case 2:
					galleryImg();
					break;
				default:
					break
			}
		})
	}

});
/*
function uploadImg(path) {
	var img = new Image();
	img.src = path;
	img.onload = function() {
		var that = this;
		//生成比例 
		var w = that.width,
			h = that.height,
			scale = w / h;
		w = 480 || w; //480  你想压缩到多大
		h = w / scale;

		//生成canvas
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		canvas.setAttribute('width', w);
		canvas.setAttribute('height', h);
		ctx.drawImage(that, 0, 0, w, h);
		var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
		//console.log(base64);
		//base64 = base64.replace('data:image/jpeg;base64,', '');
		mui.post(upurl, {
			file: base64,
			uid: uid,
			path : path
		}, function(res) {
			console.log(res.status);
			if(res.status > 0) {
				alert(res.status);
				//userinfo.avatar = '_doc/head.jpg';
				//userinfo.avatar = 'upload/avatar/' + uid + '.jpg';
				userinfo.avatar = res.surl;
				app.setState(userinfo);
				app.setUsers(userinfo);
			}
		});

	}
};

function getImage2() {
	var c = plus.camera.getCamera();
	c.captureImage(function(e) {
		plus.io.resolveLocalFileSystemURL(e, function(entry) {
			var s = entry.toLocalURL() + "?version=" + new Date().getTime();
			console.log(s);
			document.getElementById("head-img").src = s;
			uploadImg(s);
			//document.getElementById("head-img1").src = s;
			//变更大图预览的src
			//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
			document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();
		}, function(e) {
			console.log("读取拍照文件错误：" + e.message);
		});
	}, function(s) {
		console.log("error" + s);
	}, {
		filename: "_doc/head.jpg"
	})
}

function galleryImg2() {
	plus.gallery.pick(function(a) {
		plus.io.resolveLocalFileSystemURL(a, function(entry) {
			plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
				root.getFile("head.jpg", {}, function(file) {
					//文件已存在
					file.remove(function() {
						console.log("file remove success");
						entry.copyTo(root, 'head.jpg', function(e) {
								var e = e.fullPath + "?version=" + new Date().getTime();
								document.getElementById("head-img").src = e;
								uploadImg(e);
								//document.getElementById("head-img1").src = e;
								//变更大图预览的src
								//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
								document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();
							},
							function(e) {
								console.log('copy image fail:' + e.message);
							});
					}, function() {
						console.log("delete image fail:" + e.message);
					});
				}, function() {
					//文件不存在
					entry.copyTo(root, 'head.jpg', function(e) {
							var path = e.fullPath + "?version=" + new Date().getTime();
							document.getElementById("head-img").src = path;
							//document.getElementById("head-img1").src = path;
							//变更大图预览的src
							//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
							document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
						},
						function(e) {
							console.log('copy image fail:' + e.message);
						});
				});
			}, function(e) {
				console.log("get _www folder fail");
			})
		}, function(e) {
			console.log("读取拍照文件错误：" + e.message);
		});
	}, function(a) {}, {
		filter: "image"
	})
};
*/
//相册
function galleryImg() {
	plus.gallery.pick(function(a) {
		plus.io.resolveLocalFileSystemURL(a, function(entry) {　　　　　　 //entry为图片原目录（相册）流
			cutImage(entry.toLocalURL());
		}, function(e) {
			console.log("读取图片错误：" + e.message);
		});
	}, function(a) {}, {
		filter: "image"
	})
}

//拍照
function getImage() {
	var c = plus.camera.getCamera();
	c.captureImage(function(e) {
		//存储到本地
		plus.io.resolveLocalFileSystemURL(e, function(entry) {
			cutImage(entry.toLocalURL()); //裁剪图片，传入绝对地址
		}, function(e) {
			console.log("读取拍照文件错误：" + e.message);
		});
	}, function(s) {
		console.log("error" + s);
	}, {
		filename: "_doc/head.jpg"
	})
}

//裁剪图片
function cutImage(path) {
	var service_comfirm = plus.webview.getWebviewById("cropper");
	service_comfirm && plus.webview.close(service_comfirm, "none");
	mui.openWindow({
		url: 'cropper.html',
		id: 'cropper',
		extras: {
			path: path,
		},
		show: {
			aniShow: 'zoom-fade-in',
			duration: 800
		},
		waiting: {
			autoShow: true
		}
	});
}
/*
function defaultImg() {

	if(mui.os.plus) {
		plus.io.resolveLocalFileSystemURL("_doc/head.jpg", function(entry) {
			var s = entry.fullPath + "?version=" + new Date().getTime();;
			document.getElementById("head-img").src = s;
		}, function(e) {
			document.getElementById("head-img").src = '../../static/images/logo.png';
		})
	} else {
		document.getElementById("head-img").src = '../../static/images/logo.png';
	}

}
mui.plusReady(function() {
	defaultImg();
});*/